#!/usr/bin/env python3
# coding: utf-8

import os.path
import sys
import subprocess
import os
import fcntl
import re

sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
from tst_lib.ts_common import MyTestCase


class PythonTestCase(MyTestCase):
    """
    @用例ID: 20230521-200555-318402515
    @用例名称: qemu_cheak
    @用例级别: 3
    @用例标签:
    @用例类型: 功能
    """

    def tc_setup(self, *args):
        # @预置条件:
        self.msg("this is tc_setup")

    def do_test(self, *args):
        def set_no_block_read(output):
            fd = output.fileno()
            fl = fcntl.fcntl(fd,fcntl.F_GETFL)
            fcntl.fcntl(fd,fcntl.F_SETFL,fl | os.O_NONBLOCK)

        def try_read(output):
            try:
                return output.readline()
            except:
                return b''
        qemu_dir = os.environ.get('QEMU_SRC') #QEMU源码路径
        self.assert_true(qemu_dir != '')
        process = subprocess.Popen(['make','check','-j{}'.format(os.cpu_count())],stdout=subprocess.PIPE,stderr=subprocess.PIPE,cwd=qemu_dir)
        set_no_block_read(process.stdout)
        set_no_block_read(process.stderr)
        # @测试步骤: 构建qemu
        # @预期结果: qemu构建成功
        while True:
            output = try_read(process.stdout).decode('utf-8')
            if output == '' and process.poll() is not None:
                break
            if output :
                if 'Fail:               ' in output:
                    try:
                        fail = int(re.findall(r'\d+',output)[0])
                    except:
                        fail = -1
                    self.assert_true(fail == 0)
                    # 要保证错误的个数为0
                    # 如果测试失败的不是migration-test，则说明编译的QEMU有问题
                    # 如果测试失败的是migration-test，则可能是概率性问题，建议重测
                self.msg(output)
            errout = try_read(process.stderr).decode('utf-8')
            if errout :
                self.msg(errout)
        return_code = process.wait()
        self.assert_true(return_code == 0)
        # make返回值为0,即make正常完成测试

    def tc_teardown(self, *args):
        self.msg("this is tc_teardown")


if __name__ == '__main__':
    PythonTestCase().tst_main(sys.argv)
